﻿#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Web.Hosting;
#endregion

namespace pos.webserver
{

    public class HttpListenerController
    {
        private Thread _pump;
        private bool _listening = false;
        private string _virtualDir;
        private string _physicalDir;
        private string[] _prefixes;
        private HttpListenerWrapper _listener;
        private string _msg;
        public  string Msg
        {
            get { return _msg; }
        }
        public enum STATE
        {
            _error,_ok,_init
        }
        private STATE _state;
        public STATE State
        {
            get { return _state; }
        }
        public delegate void _OnErrorMsg(string msg);
        _OnErrorMsg _ErrorMsg;
        public HttpListenerController(string[] prefixes, string vdir, string pdir, _OnErrorMsg onMsg)
        {
            _prefixes = prefixes;
            _virtualDir = vdir;
            _physicalDir = pdir;
            _state = STATE._init;
            _msg = "";
            _ErrorMsg = onMsg;
        }

        public void Start()
        {
            _listening = true;
 
            _pump = new Thread(new ThreadStart(Pump));
            _pump.Start();
        }

        public void Stop()
        {
            _listening = false;

            Process.GetCurrentProcess().Kill();

            _pump.Abort();
            _pump.Join();
        }

        private void Pump()
        {
            try
            {
            
                _listener = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost(
                    typeof(HttpListenerWrapper), _virtualDir, _physicalDir);
                _listener.Configure(_prefixes, _virtualDir, _physicalDir);
                _listener.Start();
                _state = STATE._ok;
                while (_listening)
                {
                    try
                    {
                        _listener.ProcessRequest();
                    }
                    catch(Exception ex)
                    {
                        _ErrorMsg(ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                _msg = ex.ToString()+"\n";
                _state = STATE._error;
               
                EventLog myLog = new EventLog();
                myLog.Source = "HttpListenerController";
                if (null != ex.InnerException)
                    myLog.WriteEntry(ex.InnerException.ToString(), EventLogEntryType.Error);
                else
                    myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
                return;
            }

           
        }
    }

    

   
}